﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanPower.Achieve;
using CommunityToolkit.Mvvm.ComponentModel;
using static CanPower.Achieve.CANCommunitor;

namespace CanPower
{
    public class Can
    {
        //设备类型，设备索引，can通道索引
        private const uint DeviceType = 4;
        private const uint DeviceIndex = 0;
        private const uint CanIndex = 0;
        //电源控制命令的CAN ID
        private const uint PowerControlCANID = 0x100;

        //电源开关命令，假设通过数据值来控制开关
        private const byte PowerOnCommand = 0x01;
        private const byte PowerOffCommand = 0x00;
        public static void Main1(string[] args)
        {
            //尝试打开设备
            if (VCI_OpenDevice(4, 0, 1) != 1) 
            {
                Console.WriteLine("开启通道失败");
            }
            //初始化CAN通道
            VCI_INIT_CONFIG initConfig = new VCI_INIT_CONFIG
            {
                AccCode = 0x00000000,
                AccMask = 0xFFFFFFFF,
                Reserved = 0,
                Filter = 1,
                Timing0 = 0x03,
                Timing1 = 0x1C,
                Mode = 0,
            };
            if (VCI_InitCAN(DeviceType, DeviceIndex, CanIndex, ref initConfig) != 1) 
            {
                Console.WriteLine("初始化失败");
            }
            //启动CAN通道
            if(VCI_OpenDevice(DeviceType, DeviceIndex, 0) != 1)
            {
                Console.WriteLine("启动CAN通道失败");
            }
            //发送开关电源命令
            Console.WriteLine("发送电源开关命令");
            //发送电源开启命令
            SendPowerControlCommand(PowerOnCommand);
            //等待几秒钟，模拟电源开启状态
            Thread.Sleep(1000);
            //发送电源关闭命令
            SendPowerControlCommand(PowerOffCommand);
            //关闭CAN通道
            VCI_CloseDevice(DeviceType,DeviceIndex);
            Console.WriteLine("电源控制完毕，设备已关闭");
        }
        //发送电源控制命令
        private static void SendPowerControlCommand(byte command)
        {
            VCI_CAN_OBJ send =  new VCI_CAN_OBJ
            {
                ID = PowerControlCANID,//扩展帧ID（29位）
                SendType = 0,
                DataLen = 8,
                ExternFlag = 0,//标记为扩展帧
                RemoteFlag = 0,//数据帧
                Data =new byte[] { command },
                Reserved = new byte[3]
            };
            int result = VCI_Transmit(DeviceType, DeviceIndex, CanIndex, ref send, 1);
            if (result == 0)
            {
                Console.WriteLine($"发送电源控制命令：{(command == PowerOnCommand ? "开" : "关")}");
            }
            else 
            {
                Console.WriteLine("发送电源控制命令失败");
            }
        }
        /*private static bool SendMsg(uint id, byte[] data) 
        {
            VCI_CAN_OBJ send = SendPowerControlCommand(id, data);
            return VCI_Transmit(DeviceType, DeviceIndex,CanIndex, ref send, 1) ==0;
        }*/
    }
    

}
